//
//  StringExtension.swift
//  TianTianBiTing
//
//  Created by Gox mac 2 on 2019/1/2.
//  Copyright © 2019 Gox_WallyDiao. All rights reserved.
//

import Foundation
import UIKit
let dateForMatter:DateFormatter = DateFormatter.init()
let moneyForMatter:NumberFormatter = NumberFormatter.init()

extension String {
    //MARK:获得string内容高度
    //MARK:MoneyFormat
    
    static func moneyFormat(_ money: NSNumber) -> String{
        
        var num:Float = money.floatValue
        let value:Float = money.floatValue
        let scaleStr:String
        if fabsf(value) >= 100000000 {
            num = value/100000000.0
            scaleStr = "亿"
            return String.initWith(num) + scaleStr
            
        }else{
            num = value
            scaleStr = ""
            return String.money(NSNumber.init(value: num))!
            
        }
    }
    
    //MARK:时间格式化
    static func returnTimeTofammater(times:TimeInterval) -> String {
        if times==0{
            return "00:00:00"
        }
        var Min = Int(times / 60)
        let second = Int(times.truncatingRemainder(dividingBy: 60));
        var Hour = 0
        if Min>=60 {
            Hour = Int(Min / 60)
            Min = Min - Hour*60
            return String(format: "%02d : %02d : %02d", Hour, Min, second)
        }
        return String(format: "00 : %02d : %02d", Min, second)
    }
    
    static func monthForTimeStamp(_ time:UInt64) -> String? {
        dateForMatter.dateFormat = "MM-dd"
        return dateForMatter.string(from: Date.init(timeIntervalSince1970: TimeInterval(time)))
    }
    
    static func dateForTimeStamp(_ time:UInt64,dateFormat:String) -> String? {
        dateForMatter.dateFormat = dateFormat
        return dateForMatter.string(from: Date.init(timeIntervalSince1970: TimeInterval(time)))
    }
    
    static func dateIntervalForTimeStamp(_ time:UInt64) -> String? {
        if time == 0 {
            return "--"
        }
        let timeStamp = time/1000
        if timeStamp < TIMESTMP() {
            return "--"
        }
        
        let interval:UInt64 = Swift.max(0, timeStamp - TIMESTMP())
        let dayInterval = interval/24/3600
        if dayInterval == 0 {
            let house = interval/3600
            return "\(house)小时"
        }
        return "\(dayInterval)天"
    }
    
    static func getNowTime() -> String {
        let timeInterval = Date().timeIntervalSince1970
        let dateStr = timeStampToString(timeInterval)
        return dateStr
    }
    
    static func getTimeDifference(create_time:String,end_time:String) -> Int {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "YYYY-MM-dd HH:mm:ss"
        let timeNumber = Int(dateFormatter.date(from: end_time)!.timeIntervalSince1970-dateFormatter.date(from: create_time)!.timeIntervalSince1970)
        return timeNumber
        
    }
    
    static func dateIntervalToSecond(_ time:Int) -> String? {
        if time == 0 {
            return "--"
        }
      
        let dayInterval = time/60
        if dayInterval == 0 {

            return "--"
        }
        return "\(dayInterval)"
    }
    
    func trim(_ trimNewline: Bool = false) ->String {
        if trimNewline {
            return self.trimmingCharacters(in: .whitespacesAndNewlines)
        }
        
        return self.trimmingCharacters(in: .whitespaces)
    }
    
    static func timeStampToString(_ timeStamp: TimeInterval) -> String {
        let date = NSDate(timeIntervalSince1970: timeStamp)
        let dateformatter = DateFormatter()
        dateformatter.dateFormat = "YYYY-MM-dd HH:mm:ss"// 自定义时间格式
        return dateformatter.string(from: date as Date)
    }
    
    //MARK:价钱格式化
    static func money(_ money:NSNumber) -> String? {
        moneyForMatter.numberStyle = .decimal
        moneyForMatter.maximumFractionDigits = 2
        moneyForMatter.minimumFractionDigits = 2
        
        return moneyForMatter.string(from: money)
    }
    
    static func totalMoney(money:NSNumber, num:Int) -> String? {
        let newM = money.doubleValue * Double(num)
        moneyForMatter.numberStyle = .decimal
        moneyForMatter.maximumFractionDigits = 2
        moneyForMatter.minimumFractionDigits = 2
        return moneyForMatter.string(from: NSNumber.init(value: newM))
    }
    
    static func addMoney(money1:NSNumber, money2:NSNumber) -> NSNumber? {
        let money = money1.doubleValue + money2.doubleValue
        return NSNumber.init(value: money)
    }
    
    static func subtractMoney(money1:NSNumber, money2:NSNumber) -> NSNumber? {
        let money = money1.doubleValue - money2.doubleValue
        return NSNumber.init(value: money)
    }
    
    static func moneyToInt(_ money:NSNumber) -> String? {
        moneyForMatter.numberStyle = .decimal
        moneyForMatter.maximumFractionDigits = 0
        moneyForMatter.minimumFractionDigits = 0
        
        return moneyForMatter.string(from: money)
    }
    
    static func money(_ money:Double) -> String? {
        moneyForMatter.numberStyle = .decimal
        moneyForMatter.maximumFractionDigits = 2
        moneyForMatter.minimumFractionDigits = 2
        
        return moneyForMatter.string(from: NSNumber.init(value: money))
    }
    
    //加百分号%
    static func intToStringPerCen(value:Int) -> String {
        let str = String(value) + "%"
        return str
    }
    
    static func getUserId() -> Int {
        let userDefaults = UserDefaults.standard
        let userId = userDefaults.integer(forKey: "userId")
        
        return userId
    }
    
    static func getJpushId() -> String {
        let userDefaults = UserDefaults.standard
        let userId = userDefaults.string(forKey: "RegistrationID")
        
        return userId ?? "0"
    }
    
    static func getUserIdToString() -> Bool {
        let userDefaults = UserDefaults.standard
        let userId = userDefaults.integer(forKey: "userId")
        let str = "\(userId)"
        if str == "" || str == "0" {
            return false
        } else {
            return true
        }
    }
    
    //浮点数转成俩位数字符串
    static func floatToString(value:Double) -> String {
        let roundDown = NSDecimalNumberHandler(roundingMode: .down, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
        let valueTmp = NSDecimalNumber(string: "1")
        let strTmp = NSDecimalNumber(value: value)
        let result = strTmp.multiplying(by: valueTmp, withBehavior: roundDown)
        return String(format:"%.2f", result.doubleValue)
    }
    //字符串转成浮点数
    static func stringToFloatWithTwoDecimals(value:String) -> Double {
        let roundDown = NSDecimalNumberHandler(roundingMode: .down, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
        let valueTmp = NSDecimalNumber(string: "1")
        let strTmp = NSDecimalNumber(string: value)
        let result = strTmp.multiplying(by: valueTmp, withBehavior: roundDown)
        return result.doubleValue
    }
    //字符串截取成俩位字符串
    static func stringToStringWithTwoDecimals(value:String) -> String {
        return String(format:"%.2f", stringToFloatWithTwoDecimals(value:value))
    }
    
    //从后台拿到的数据有精度丢失，先校验后使用
    static func reviseString(oString:String?) -> String? {
        guard let oString = oString else { return nil }
        let testDouble = oString.doubleValue()
        let doubleStr = ("\(testDouble)")
        let decNumber =  NSDecimalNumber(string: doubleStr)
        return String(format:"%.2f", decNumber.doubleValue)
    }
    //从后台拿到的数据直接校验然后转成金钱格式
//    static func reviseFormatMoney(oString:String?) -> String {
//        let rString = reviseString(oString: oString)
//        if rString != nil {
//            return String.moneyFormat(rString!)
//        } else {
//            return "--"
//        }
//    }
    
    //价格格式化
//    static func priceFormat(price:String?) -> String {
//        guard let price = price else { return "--" }
//        return String.moneyFormat(String.stringToStringWithTwoDecimals(value: price))
//    }
    
    func stringHeightWith(fontSize:CGFloat,width:CGFloat)->CGFloat{
        
        let font = UIFont.systemFont(ofSize: fontSize)
        
        let size = CGSize.init(width: width, height:CGFloat.greatestFiniteMagnitude)
        
        let paragraphStyle = NSMutableParagraphStyle()
        
        paragraphStyle.lineBreakMode = .byWordWrapping;
        
        let attributes = [NSAttributedString.Key.font:font, NSAttributedString.Key.paragraphStyle:paragraphStyle.copy()]
        
        let text = self as NSString
        
        let rect = text.boundingRect(with: size, options:.usesLineFragmentOrigin, attributes: attributes, context:nil)
        
        if rect.size.height < 15.0 {
            return 18
        } else {
            return 35
        }
        
//        return rect.size.height
        
    }//funcstringHeightWith
    
    func integerValue() -> Int {
        return  (self as NSString).integerValue
    }
    func doubleValue() -> Double {
        return  (self as NSString).doubleValue
    }
    
    func floatValue() -> Float {
        return  (self as NSString).floatValue
    }
    
    func uint64Value() -> UInt64 {
        return  UInt64((self as NSString).integerValue)
    }
    
    func toDic() ->NSDictionary{
        
        let jsonData:Data = self.data(using: .utf8)!
        
        let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if dict != nil {
            return dict as! NSDictionary
        }
        return NSDictionary()
    }
    
    static func initWith(_ value :Float) -> String{
        return String.init(format: "%0.2f", value)
    }
    
    static func initWith(_ value :Float,_ keep:Int) -> String{
        return String.init(format: "%.\(keep)f", value)
    }
    
    static func initWith(_ value :Double,_ keep:Int) -> String{
        return String.init(format: "%.\(keep)f", value)
    }
    
    static func initWith(_ value :Int) -> String{
        return String.init(format: "%d", value)
    }
    static func initWith(_ value :Double) -> String{
        return String.init(format: "%0.2f", value)
    }
    static func initWith(_ value :UInt64) -> String{
        return String.init(format: "%d", value)
    }
    static func initWith(_ value :NSNumber) -> String{
        return String.init(format: "%d", value.uint64Value)
    }
    
//    static func moneyFormat(_ value:String?) -> String {
//        guard let valueTmp = value else { return "--" }
//        if valueTmp == "null" {
//            return "--"
//        }

//        return money(NSNumber.initWith(str: valueTmp))!
//    }
    
    static func moneyToDecimalNumber(_ value:String?) -> NSDecimalNumber? {
        let roundDown = NSDecimalNumberHandler(roundingMode: .down, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
        let valueTmp = NSDecimalNumber(string: "1")
        let strTmp = NSDecimalNumber(string: value)
        let result = strTmp.multiplying(by: valueTmp, withBehavior: roundDown)
        return result
    }
    
    //判断字符串是否为空
    static func isNull(str:String?) -> Bool {
        guard let str = str else { return true }
        if str == "null" || str == "nil" || str == "" {
            return true
        }
        
        return false
    }
    
}

extension String {
    /// 修正图片的剪裁参数
    func amendPictureUrl(_ size:CGSize) -> String {
        
        if !self.contains("h_") { return self }
        let range = (self as NSString).range(of: "h_")
        let goodPic = (self as NSString).replacingCharacters(in: NSMakeRange(range.location, (self.characters).count - range.location), with: "h_\(Int(size.width * UIScreen.main.scale)),w_\(Int(size.width * UIScreen.main.scale))")
        return goodPic
    }
}
